Lumen & Gesso / website · lumengesso.com / app / api / admin / orders / [id] / generate / route.ts
| 1 | import { NextResponse, type NextRequest } from 'next/server'; |
| 2 | import { getCustomerUser } from '@/app/lib/lumen-auth'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { isAdmin } from '@/app/lib/admin'; |
| 5 | import { generateImage, fetchReference, buildCustomerRevisionPrompt, buildRefinePrompt, buildChainRefinePrompt, aspectSpecFromFrame, withAspect } from '@/app/lib/image-gen'; |
| 6 | import { OPENAI_IMAGE_MODEL, resolveImageModel, SUPPORTED_MODELS, type ImageModel } from '@/app/lib/image-models'; |
| 7 | import { cropToAspect } from '@/app/lib/image-crop'; |
| 8 | import { downloadOriginalImage, uploadImage } from '@/app/lib/cf-images'; |
| 9 | import { frameAspect, type ProductId, type Orientation } from '@/app/lib/pricing'; |
| 10 | import { activeProofRevision, customerRevisions, orderMessageConfig, ORDER_MESSAGE_LIMIT, type PrintUpscale } from '@/app/lib/order-messages'; |
| 11 | import { prepareWiderFraming, requestsWiderFraming } from '@/app/lib/revision-framing'; |
| 12 | import { encodePhotoJpeg, imageDimensions, upscalePrintImage } from '@/app/lib/image-processing'; |
| 13 | |
| 14 | export const runtime = 'nodejs'; |
| 15 | export const dynamic = 'force-dynamic'; |
| 16 | export const maxDuration = 120; |
| 17 | const PRINT_LONG_EDGE = 4096; |
| 18 | |
| 19 | /** Encode a generated master as a high-quality JPEG for upload. Raw 4K |
| 20 | * PNGs routinely exceed Cloudflare Images' 20 MB ceiling (multi-pet |
| 21 | * renders are the most detailed → largest), which fails the upload. |
| 22 | * q90 mozjpeg keeps the full 4K resolution for print while landing at a |
| 23 | * few MB. These are opaque photographic prints, so PNG's losslessness / |
| 24 | * alpha buys nothing here; flatten any stray alpha onto white. */ |
| 25 | async function toUploadJpeg(bytes: Buffer): Promise<Buffer> { |
| 26 | return encodePhotoJpeg(bytes, 90); |
| 27 | } |
| 28 | |
| 29 | /** Shared post-processing tail for every generation path (fresh, refine, |
| 30 | * chain): crop the AI's square output to the customer's frame aspect, |
| 31 | * upload the clean file, and insert a generations row. Returns the inserted gen or throws. */ |
| 32 | async function finalizeGeneration(args: { |
| 33 | admin: ReturnType<typeof commerceDb>; |
| 34 | orderId: string; |
| 35 | model: string; |
| 36 | prompt: string; |
| 37 | rawBytes: Buffer; |
| 38 | targetAspect: string | null; |
| 39 | setStage: (stage: string) => void; |
| 40 | printSize?: PrintUpscale['upscaled']; |
| 41 | }) { |
| 42 | const { admin, orderId, model, prompt, rawBytes, targetAspect, setStage, printSize } = args; |
| 43 | setStage('prepare preview'); |
| 44 | // Crop the AI's square output to the customer's frame aspect so the |
| 45 | // stored file (which Prodigi prints) matches what they'll receive. |
| 46 | // No-op if aspect already matches. Proofs are shown clean: there is no |
| 47 | // watermark, so the customer sees exactly the artwork we print. |
| 48 | const cleanBytes = targetAspect ? await cropToAspect(rawBytes, targetAspect) : rawBytes; |
| 49 | |
| 50 | // Encode to JPEG before upload — a 4K PNG can exceed CF Images' 20 MB |
| 51 | // limit. JPEG preserves the full 4K resolution at a fraction of the size. |
| 52 | const cleanJpeg = await toUploadJpeg(cleanBytes); |
| 53 | |
| 54 | setStage('upload images'); |
| 55 | const clean = await uploadImage(cleanJpeg, { filename: `${orderId}-clean.jpg`, metadata: { kind: 'generation_clean', order: orderId } }); |
| 56 | |
| 57 | if (printSize) { |
| 58 | setStage('verify delivered print resolution'); |
| 59 | const delivered = await fetchReference(clean.printUrl); |
| 60 | const { width, height } = await imageDimensions(delivered.bytes); |
| 61 | if (width !== printSize.width || height !== printSize.height) { |
| 62 | throw new Error('The print file did not retain the enlarged dimensions in delivery. Your draft is still available.'); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | setStage('save render'); |
| 67 | const { data: gen, error: insErr } = await admin |
| 68 | .from('generations') |
| 69 | .insert({ |
| 70 | order_id: orderId, |
| 71 | prompt, |
| 72 | model, |
| 73 | clean_url: printSize ? clean.printUrl : clean.publicUrl, |
| 74 | // Legacy column: now the clean preview URL (no watermark). |
| 75 | watermarked_url: clean.publicUrl, |
| 76 | published: false, |
| 77 | }) |
| 78 | .select('id, clean_url, watermarked_url, created_at, model') |
| 79 | .single(); |
| 80 | |
| 81 | if (insErr || !gen) throw new Error(`db insert failed: ${insErr?.message}`); |
| 82 | return gen; |
| 83 | } |
| 84 | |
| 85 | async function saveRevisionDraft( |
| 86 | admin: ReturnType<typeof commerceDb>, |
| 87 | orderId: string, |
| 88 | baseGenerationId: string, |
| 89 | feedbackAt: string, |
| 90 | generationId: string, |
| 91 | replaceDraftId: string | null, |
| 92 | printUpscale?: Omit<PrintUpscale, 'generationId'>, |
| 93 | ) { |
| 94 | // Chat replies also write order config. Re-read after generation and use |
| 95 | // the existing optimistic update so those replies are preserved. |
| 96 | for (let attempt = 0; attempt < 3; attempt += 1) { |
| 97 | const { data: order, error } = await admin.from('orders') |
| 98 | .select('status, current_generation_id, config, revision_note, updated_at').eq('id', orderId).single(); |
| 99 | if (error || !order) throw new Error('Could not save the revision draft.'); |
| 100 | const revision = activeProofRevision(order); |
| 101 | if (revision?.baseGenerationId !== baseGenerationId || revision.feedback.at !== feedbackAt) return null; |
| 102 | if (printUpscale && revision.draftId !== replaceDraftId) return null; |
| 103 | if (printUpscale && revision.printUpscale) return revision.printUpscale.generationId; |
| 104 | if (revision.draftId !== replaceDraftId) return revision.draftId; |
| 105 | const { data: saved, error: saveError } = await admin.from('orders').update({ |
| 106 | config: { |
| 107 | ...orderMessageConfig(order.config), |
| 108 | revisions: customerRevisions(order.config, order.revision_note, order.updated_at), |
| 109 | revisionDraft: { |
| 110 | generationId: printUpscale ? revision.draftId! : generationId, baseGenerationId, feedbackAt, |
| 111 | ...(printUpscale ? { printUpscale: { ...printUpscale, generationId } } : {}), |
| 112 | }, |
| 113 | }, |
| 114 | }).eq('id', orderId).eq('status', order.status).eq('current_generation_id', baseGenerationId) |
| 115 | .eq('updated_at', order.updated_at).select('id').maybeSingle(); |
| 116 | if (saveError) throw new Error('Could not save the revision draft.'); |
| 117 | if (saved) return generationId; |
| 118 | } |
| 119 | return null; |
| 120 | } |
| 121 | |
| 122 | export async function POST( |
| 123 | req: NextRequest, |
| 124 | ctx: { params: Promise<{ id: string }> }, |
| 125 | ) { |
| 126 | const { id } = await ctx.params; |
| 127 | const incomingId = req.headers.get('x-generation-attempt'); |
| 128 | const attemptId = incomingId && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(incomingId) |
| 129 | ? incomingId |
| 130 | : crypto.randomUUID(); |
| 131 | const startedAt = Date.now(); |
| 132 | const reject = (error: string, status: number, reason: string) => { |
| 133 | console.warn('[portrait generation] request rejected', { attemptId, status, reason }); |
| 134 | return NextResponse.json({ error, attemptId }, { status }); |
| 135 | }; |
| 136 | |
| 137 | const user = await getCustomerUser(); |
| 138 | if (!user || !isAdmin(user.email)) { |
| 139 | return reject('Your studio session is missing or expired. Sign in again and retry.', 403, 'not authorized'); |
| 140 | } |
| 141 | |
| 142 | let body: { model?: unknown; prompt?: unknown; baseGenerationId?: unknown; finish?: unknown; upscale?: unknown; feedbackAt?: unknown; replaceDraftId?: unknown } | null; |
| 143 | try { |
| 144 | body = await req.json(); |
| 145 | } catch { |
| 146 | return reject('Invalid generation request.', 400, 'invalid json'); |
| 147 | } |
| 148 | |
| 149 | const model = resolveImageModel(body?.model); |
| 150 | if (!model) { |
| 151 | return reject(`Select a supported model: ${SUPPORTED_MODELS.join(', ')}.`, 400, 'unsupported model'); |
| 152 | } |
| 153 | const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : ''; |
| 154 | |
| 155 | // Refine + finish both steer on a PRIOR generation instead of the pet |
| 156 | // photo. The reference becomes that render's clean file. |
| 157 | // • Refine: `prompt` is the admin's tweak ("same but red background"), |
| 158 | // wrapped into an edit instruction; runs on the chosen model. |
| 159 | // • Finish: re-render the existing image through OpenAI |
| 160 | // to tighten the finish ("make one like this"). Supplies its own |
| 161 | // prompt, so no user text is required. |
| 162 | const baseGenerationId = typeof body?.baseGenerationId === 'string' ? body.baseGenerationId : null; |
| 163 | const feedbackAt = body?.feedbackAt; |
| 164 | const replaceDraftId = typeof body?.replaceDraftId === 'string' ? body.replaceDraftId : null; |
| 165 | const finish = body?.finish === true; |
| 166 | const upscale = body?.upscale === true; |
| 167 | if (upscale && (typeof feedbackAt !== 'string' || !replaceDraftId || finish)) { |
| 168 | return reject('Select a revision draft to upscale.', 400, 'missing upscale draft'); |
| 169 | } |
| 170 | if (feedbackAt !== undefined && (typeof feedbackAt !== 'string' || !baseGenerationId || finish || prompt.length > ORDER_MESSAGE_LIMIT)) { |
| 171 | return reject('Select the current proof and customer feedback.', 400, 'invalid revision'); |
| 172 | } |
| 173 | if (finish && !baseGenerationId) { |
| 174 | return reject('Select a render to finish.', 400, 'finish missing base'); |
| 175 | } |
| 176 | // Fresh + refine need a prompt; finish builds its own. |
| 177 | if (!finish && !prompt && feedbackAt === undefined) return reject('Enter a prompt to generate.', 400, 'missing prompt'); |
| 178 | console.info('[portrait generation] started', { attemptId, model, action: upscale ? 'upscale' : finish ? 'finish' : baseGenerationId ? 'refine' : 'generate' }); |
| 179 | |
| 180 | const admin = commerceDb(); |
| 181 | const { data: order, error: orderErr } = await admin |
| 182 | .from('orders') |
| 183 | .select('id, pet_photo_urls, custom_style_url, config, status, current_generation_id, revision_note, updated_at') |
| 184 | .eq('id', id) |
| 185 | .single(); |
| 186 | if (orderErr || !order) return reject('Could not load the order.', orderErr && orderErr.code !== 'PGRST116' ? 500 : 404, orderErr?.code ?? 'missing order'); |
| 187 | const revision = feedbackAt === undefined ? null : activeProofRevision(order); |
| 188 | if (feedbackAt !== undefined && (!revision || revision.baseGenerationId !== baseGenerationId || revision.feedback.at !== feedbackAt)) { |
| 189 | return reject('The proof or customer feedback changed. Reopen the order and try again.', 409, 'stale revision'); |
| 190 | } |
| 191 | if (revision && replaceDraftId && revision.draftId !== replaceDraftId) { |
| 192 | return reject('The draft changed. Review the latest draft before generating again.', 409, 'stale draft'); |
| 193 | } |
| 194 | if (upscale && revision?.printUpscale) return NextResponse.json({ generation: { id: revision.printUpscale.generationId }, attemptId }); |
| 195 | if (revision?.draftId && !replaceDraftId) return NextResponse.json({ generation: { id: revision.draftId }, attemptId }); |
| 196 | |
| 197 | // Resolve the customer's chosen frame aspect from the order config. |
| 198 | // We crop the AI output to this aspect so the file Prodigi prints |
| 199 | // is exactly what the customer previewed inside their frame mock. |
| 200 | const cfg = (order.config ?? {}) as { productId?: ProductId; size?: string; orientation?: Orientation; pets?: Array<{ slot?: number; name?: string }> }; |
| 201 | // Landscape orders transpose the size's aspect — the crop + native |
| 202 | // generation shape follow the orientation the customer chose. |
| 203 | const targetAspect = frameAspect(cfg.productId, cfg.size, cfg.orientation ?? 'portrait'); |
| 204 | // Generate natively in the frame's shape (model config below) and crop |
| 205 | // to the exact frame aspect afterward. aspectSpec snaps the frame ratio |
| 206 | // to the nearest each model supports. |
| 207 | const aspectSpec = aspectSpecFromFrame(targetAspect); |
| 208 | |
| 209 | let stage = 'load references'; |
| 210 | const setStage = (value: string) => { |
| 211 | stage = value; |
| 212 | console.info('[portrait generation] stage', { attemptId, stage, elapsedMs: Date.now() - startedAt }); |
| 213 | }; |
| 214 | try { |
| 215 | if (upscale && revision?.draftId) { |
| 216 | const { data: draft, error: draftError } = await admin.from('generations') |
| 217 | .select('clean_url, model').eq('id', revision.draftId).eq('order_id', id).single(); |
| 218 | if (draftError || !draft?.clean_url) return reject('The revision draft could not be loaded.', 404, 'missing upscale source'); |
| 219 | |
| 220 | setStage('load full-resolution draft'); |
| 221 | const source = await downloadOriginalImage(draft.clean_url); |
| 222 | const { width, height } = await imageDimensions(source); |
| 223 | if (!width || !height) throw new Error('Could not read the draft image dimensions.'); |
| 224 | if (Math.max(width, height) >= PRINT_LONG_EDGE) { |
| 225 | return reject(`The revision draft is already ${width} × ${height} px. It meets the 4,096 px print target.`, 422, 'already print size'); |
| 226 | } |
| 227 | |
| 228 | setStage('upscale print image'); |
| 229 | const result = await upscalePrintImage(source, { width, height }, PRINT_LONG_EDGE); |
| 230 | const original = { width, height }; |
| 231 | const upscaled = { width: result.info.width, height: result.info.height }; |
| 232 | const generation = await finalizeGeneration({ |
| 233 | admin, orderId: id, model: draft.model, rawBytes: result.data, targetAspect: null, printSize: upscaled, setStage, |
| 234 | prompt: `Print upscale: ${width} × ${height} px to ${upscaled.width} × ${upscaled.height} px. Source draft: ${revision.draftId}.`, |
| 235 | }); |
| 236 | const draftId = await saveRevisionDraft(admin, id, revision.baseGenerationId, revision.feedback.at, |
| 237 | generation.id, revision.draftId, { original, upscaled }); |
| 238 | if (!draftId) return reject('The revision draft changed while upscaling.', 409, 'upscale source changed'); |
| 239 | return NextResponse.json({ generation: { id: draftId }, attemptId }); |
| 240 | } |
| 241 | |
| 242 | // ── Resolve the reference image, model, and prompt for this pass ── |
| 243 | let ref: { bytes: Buffer; mime: 'image/png' | 'image/jpeg' }; |
| 244 | let additionalSubjectRefs: Array<{ bytes: Buffer; mime: 'image/png' | 'image/jpeg' }> = []; |
| 245 | let subjectLabels: string[] = []; |
| 246 | let styleRef: { bytes: Buffer; mime: 'image/png' | 'image/jpeg' } | null = null; |
| 247 | let genModel: ImageModel = model; |
| 248 | let genPrompt = prompt; |
| 249 | let storedModel: string = model; |
| 250 | |
| 251 | if (baseGenerationId) { |
| 252 | // Refine + finish steer on a prior render — the reference is that |
| 253 | // generation's clean file. No custom-style ref on this path. |
| 254 | const { data: baseGen, error: baseErr } = await admin |
| 255 | .from('generations') |
| 256 | .select('id, clean_url, model') |
| 257 | .eq('id', baseGenerationId) |
| 258 | .eq('order_id', order.id) |
| 259 | .single(); |
| 260 | if (baseErr || !baseGen?.clean_url) { |
| 261 | return reject('The selected render could not be loaded.', baseErr && baseErr.code !== 'PGRST116' ? 500 : 404, baseErr?.code ?? 'missing base render'); |
| 262 | } |
| 263 | ref = await fetchReference(baseGen.clean_url); |
| 264 | |
| 265 | if (finish) { |
| 266 | // Use the current OpenAI model with the route's OpenAI output size. |
| 267 | // Keep the source model in the label so the history shows both passes. |
| 268 | genModel = OPENAI_IMAGE_MODEL; |
| 269 | genPrompt = withAspect(buildChainRefinePrompt(), aspectSpec); |
| 270 | storedModel = baseGen.model ? `${baseGen.model}→${genModel}` : genModel; |
| 271 | } else { |
| 272 | // Refine: the admin's tweak, wrapped into an edit instruction |
| 273 | // (+ frame-aspect directive), on the same engine that produced |
| 274 | // the render. |
| 275 | if (revision) { |
| 276 | genModel = resolveImageModel(baseGen.model) ?? OPENAI_IMAGE_MODEL; |
| 277 | storedModel = genModel; |
| 278 | const widerFraming = (order.pet_photo_urls?.length ?? 0) <= 1 && requestsWiderFraming(revision.feedback.note); |
| 279 | if (widerFraming) { |
| 280 | ref = { bytes: await prepareWiderFraming(ref.bytes), mime: 'image/jpeg' }; |
| 281 | } |
| 282 | genPrompt = buildCustomerRevisionPrompt(revision.feedback.note, prompt, aspectSpec, widerFraming); |
| 283 | } else { |
| 284 | genPrompt = withAspect(buildRefinePrompt(prompt), aspectSpec); |
| 285 | } |
| 286 | } |
| 287 | } else { |
| 288 | // Fresh mode: subject pet photo(s) + (custom-style commissions) the |
| 289 | // customer-uploaded style ref, fetched in parallel. EVERY uploaded |
| 290 | // pet photo feeds the model so it composites them into one portrait |
| 291 | // — the customer paid per pet, and the prompt's multi-pet language |
| 292 | // only does anything if all the pets actually reach the model. |
| 293 | // Gemini gets the style ref as the final positional reference; |
| 294 | // OpenAI ignores it. |
| 295 | const photos = (order.pet_photo_urls as string[]) ?? []; |
| 296 | if (photos.length === 0) return reject('This order has no reference photo.', 400, 'missing reference photo'); |
| 297 | |
| 298 | // Best-effort pet names (positional) to label each subject in the |
| 299 | // reference header — blank entries fall back to a generic label. |
| 300 | // Upload order is preserved so image 1 is pet 1. |
| 301 | const petNames = (cfg.pets ?? []).map(p => (p?.name ?? '').trim()); |
| 302 | subjectLabels = photos.map((_, i) => petNames[i] ?? ''); |
| 303 | |
| 304 | const customStyleUrl = (order.custom_style_url as string | null) ?? null; |
| 305 | const [subjectRefs, s] = await Promise.all([ |
| 306 | Promise.all(photos.map(p => fetchReference(p))), |
| 307 | customStyleUrl ? fetchReference(customStyleUrl) : Promise.resolve(null), |
| 308 | ]); |
| 309 | ref = subjectRefs[0]; |
| 310 | additionalSubjectRefs = subjectRefs.slice(1); |
| 311 | styleRef = s; |
| 312 | } |
| 313 | |
| 314 | // Use the same render for the proof preview and the print file. |
| 315 | setStage('generate image'); |
| 316 | const rawBytes = await generateImage({ |
| 317 | model: genModel, |
| 318 | prompt: genPrompt, |
| 319 | referenceBytes: ref.bytes, |
| 320 | referenceMime: ref.mime, |
| 321 | additionalSubjectReferences: additionalSubjectRefs, |
| 322 | subjectLabels, |
| 323 | styleReferenceBytes: styleRef?.bytes, |
| 324 | styleReferenceMime: styleRef?.mime, |
| 325 | // Frame-shape-aware: Gemini uses aspectRatio, OpenAI uses size. |
| 326 | aspectRatio: aspectSpec.gemini, |
| 327 | size: aspectSpec.openaiSize, |
| 328 | geminiImageSize: '4K', |
| 329 | }); |
| 330 | |
| 331 | const gen = await finalizeGeneration({ |
| 332 | admin, |
| 333 | orderId: order.id, |
| 334 | model: storedModel, |
| 335 | prompt: genPrompt, |
| 336 | rawBytes, |
| 337 | targetAspect, |
| 338 | setStage, |
| 339 | }); |
| 340 | |
| 341 | console.info('[portrait generation] saved', { attemptId, model: storedModel, generationId: gen.id, elapsedMs: Date.now() - startedAt }); |
| 342 | if (!revision) return NextResponse.json({ generation: gen, attemptId }); |
| 343 | const draftId = await saveRevisionDraft(admin, order.id, revision.baseGenerationId, revision.feedback.at, gen.id, replaceDraftId); |
| 344 | if (!draftId) return reject('The proof changed while the revision rendered. Reload the order to review its latest state.', 409, 'revision changed while rendering'); |
| 345 | return NextResponse.json({ generation: { id: draftId }, attemptId }); |
| 346 | } catch (e) { |
| 347 | const msg = e instanceof Error ? e.message : String(e); |
| 348 | console.error('[portrait generation] failed', { attemptId, model, stage, elapsedMs: Date.now() - startedAt, errorType: e instanceof Error ? e.name : 'Unknown' }); |
| 349 | return NextResponse.json({ error: msg, attemptId }, { status: 500 }); |
| 350 | } |
| 351 | } |